<template>
  <div class="container-fluid H100 root" v-on:dragover.prevent v-on:drop.prevent="onDrop" v-on:click="debug">
    <div v-for="(item, i) in items" :key="i" v-on:click="selectRow(i)">
      <draggable element="div" v-model="item.data" :options="dragOptions" :move="onMove" @start="onStart" @end="isDragging=false">
        <transition-group class="row" type="transition" :name="'flip-list'" :class="{ rowSel: rowSelIndex===i && rowSelMode }">
          <div v-for="d in item.data" :class="['col-'+d.col, 'node']" :key="d.id" v-on:click="selectView(d.id)">
            <!--具体绘图容器-->
            <div :id="d.id" :class="['view', d.id===viewSelId ? 'viewSel' : '']" v-on:dragover.prevent @drop.prevent="dropImage"></div>
          </div>
        </transition-group>
      </draggable>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import Chart from '../chart/chart';
import * as Util from '../js/util';

export default {
  name: 'Center',
  components: {
    draggable
  },
  data: function () {
    return {
      cacheDrag: {
        src: '',
        to: ''
      },
      count: 0,
      editable: true,
      delayedDragging: false,
      rowSelMode: false,
      rowSelIndex: -1,
      viewSelId: '',
      items: [
        {
          data: [{id: 'v1', col: '6'}, {id: 'v2', col: '6'}]
        }
      ],
      id: '0',
      // 未执行任务队列
      // 容器数据还未更新至视图时，绘图操作无效，故需要暂时放入队列等updated之后执行。
      queue: []
    }
  },
  mounted: function () {
    this.id = Util.getParameterByName('id') || '';
    if (this.id && this.id.toString().length > 4) {
      this.loadProject();
    } else {
      Chart.project.layout = this.items;
    }
  },
  methods: {
    // 用于拖拽时即选中
    onStart: function (event) {
      let id = $(event.target).find('.view').attr('id');
      if (id !== '') this.viewSelId = id;
      this.isDragging = true;
    },
    onMove: function ({relatedContext, draggedContext}) {
      const relatedElement = relatedContext.element;
      const draggedElement = draggedContext.element;
      this.cacheDrag.src = relatedElement.id;
      this.cacheDrag.to = draggedElement.id;

      return (!relatedElement || !relatedElement.fixed) && !draggedElement.fixed;
    },
    // 容器拖拽放置
    onDrop: function (ev) {
      let str = ev.dataTransfer.getData('Text');
      if (str.indexOf('visual') === -1) {
        return;
      }
      // 确定来源为容器
      let id = 'view' + (++this.count) + '_';
      let sps = str.replace('visual', '').split(' ');
      let cols = sps.filter(function (d) { return d !== ''; })
        .map((d, i) => ({ 'id': id + i, 'col': parseInt(d) }));
      this.items.push({ data: cols });
      this.rowSelIndex = this.items.length - 1;
    },
    selectRow: function (i) {
      this.rowSelIndex = i;
      // console.log(i);
    },
    selectView: function (id) { // event
      if (id) {
        if (id in Chart.instances) Chart.current.id = id;
        this.viewSelId = id;
      }
    },
    // 图形控件
    dropImage: function (ev) {
      let str = ev.dataTransfer.getData('Text');
      if (str.indexOf('graph') === -1) {
        return;
      }
      let name = str.replace('graph', '');
      let id = $(ev.target).attr('id');
      // 容器有图存在时
      if ($(ev.target)[0].tagName === 'CANVAS') {
        id = $(ev.target).parents('div.view').attr('id');
        let asw = window.confirm('确定要删除原来的图形吗（该操作不可撤销）？');
        if (!asw) return;
      }

      Chart.components[name].draw(id);
    },
    // 加载项目信息
    loadProject: function () {
      let $this = this;
      Util.ajaxData('getProjrctInfo', {projectId: this.id}, (rst) => {
        console.log(rst);
        if (rst.status.code === 0) {
          let p = rst.data;
          Chart.project = {
            name: p.name,
            describe: p.description,
            layout: p.layout
          };
          $this.items = p.layout;
          $this.count = $this.items.length;
          p.data.forEach((d) => {
            $this.queue.push(function () {
              Chart.draw(d.colId, d.option, d.name, d.key, d.describe, d.url);
            });
          });
        } else {
          alert(rst.status.message);
        }
      });
    },
    debug: function () {
      console.log(Chart);
      this.items.map(function (d) {
        // console.log(d);
      });
    }
  },
  computed: {
    dragOptions: function () {
      return {
        animation: 150,
        group: 'description',
        disabled: !this.editable,
        ghostClass: 'ghost',
        dragClass: 'dragClass'
      };
    }
  },
  watch: {
    isDragging: function (newValue) {
      if (newValue) {
        this.delayedDragging = true;
        return;
      }
      this.$nextTick(() => {
        this.delayedDragging = false;
      })
    },
    // 传给全局变量，用于项目信息保存入库
    'items': {
      handler: function () {
        Chart.project.layout = this.items;
      },
      deep: true
    }
  },
  // 视图刷新时执行
  updated: function () {
    if (this.queue.length === 0) return;
    while (this.queue.length > 0) {
      this.queue.pop()();
    }
    Chart.status.flag = 1;
  }
}

</script>

<style scoped>
  .node{ min-height: 400px; margin:0px; padding:1px;border: 1px solid #eeeeee; }
  .f{ float: left }
  .rowSel{ border:1px solid #28a745 }
  .root{ padding-top:5px; }
  .ghost{ opacity:1; background-color: #eee }
  .dragClass { opacity:1; border:1px solid #a94442; background-color: #ddd }
  .viewSel{ border:1px solid #a94442 }
  .view{
    width:100%;
    height:100%;
    border-radius:5px;
    -moz-border-radius:5px; /* 老的 Firefox */
  }
</style>
